const {resolve} = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCSSExtractPlugin = require('mini-css-extract-plugin')
const optimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');

// nodejs环境, 指定postcss兼容browserslist的production配置
process.env.NODE_ENV = 'production'

const commonCssLoader = [
  {
    loader: MiniCSSExtractPlugin.loader,
    options: {
      publicPath: '../'
    }
  },
  'css-loader',
  {
    // 须在package.json中定义browserslist
    loader: 'postcss-loader',
    options: {
      ident: 'postcss',
      plugins: () => [
        require('postcss-preset-env')()
      ]
    }
  },
]

module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: "js/bundle.js",
    path: resolve(__dirname, 'build')
  },
  module: {
    rules: [
      /*
        同一类型文件(.js)如果指定多条规则, 一定要指定执行顺序
         */
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
        enforce: "pre", // 优先执行
        options: {
          fix: true,  // 自动修复
        }
      },
      // 常规情况下,对于一个文件会对所有的rules匹配一遍,实际上很多情况下只要匹配到1个就不用再继续匹配了
      // oneOf就是只匹配其中一个的意思,里面不能有针对同一文件的不同配置(这个时候需要提到外面)
      {
        oneOf: [
          {
            test: /\.less$/,
            use: [
              ...commonCssLoader,
              'less-loader'
            ]
          },
          {
            test: /\.css$/,
            use: [
              ...commonCssLoader
            ]
          },
          {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            options: {
              presets: [
                ['@babel/preset-env',
                  {
                    useBuiltIns: 'usage',
                    corejs: {version: 3},
                    targets: {
                      chrome: '50',
                      firefox: '28',
                      ie: '9'
                    }
                  }
                ]
              ]
            }
          },
          {
            test: /\.(jpg|png|jpeg|gif)$/,
            loader: 'url-loader',
            options: {
              limit: 8 * 1024,
              outputPath: 'imgs'
            }
          },
          {
            test: /\.html/, loader: 'html-loader',
          },
          {
            exclude: /\.(html|js|css|less|jpg|png|jpeg|gif)$/,
            loader: 'file-loader',
            options: {
              outputPath: 'media'
            }
          }
        ]
      },

    ]
  },
  plugins: [
    new HtmlWebpackPlugin(
      {
        template: './src/index.html',
        minify: true
      }
    ),
    new MiniCSSExtractPlugin({
      filename: 'css/built.css'
    }),
    new optimizeCssAssetsWebpackPlugin()
  ],
  mode: "production"
}